<template>
  <el-dialog v-model="isShow" title="添加里程碑" width="40%" :before-close="handleClose">
    <el-form ref="formRef" :model="form" label-width="100px">
      <el-form-item label="里程碑名称" prop="name" required>
        <el-input v-model="form.name" placeholder="请输入里程碑名称" />
      </el-form-item>

      <el-form-item v-if="postOptions.length > 0" label="关联文章" prop="postId">
        <el-select v-model="form.postId" placeholder="请选择关联文章">
          <el-option
            v-for="post in postOptions"
            :key="post.id"
            :label="post.title"
            :value="post.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="里程碑日期" prop="date" required>
        <el-date-picker
          v-model="form.date"
          type="date"
          placeholder="选择日期"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>

      <el-form-item label="重要性" prop="priority">
        <el-rate v-model="form.priority" :max="3" />
      </el-form-item>

      <el-form-item label="描述" prop="description">
        <el-input
          v-model="form.description"
          type="textarea"
          :rows="3"
          placeholder="请输入里程碑描述"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleSave">保存</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';
import { useGanttStore } from '@/store/modules/ganttStore';

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  postId: {
    type: String,
    default: null
  }
});

const emit = defineEmits(['save', 'close']);

const isShow = ref(props.visible);
const store = useGanttStore();
const formRef = ref();
const form = ref({
  name: '',
  postId: props.postId || null,
  date: '',
  priority: 1,
  description: ''
});

const postOptions = computed(() => store.posts);

const handleClose = () => {
  emit('close');
};

const handleSave = async () => {
  const isValid = await formRef.value.validate();
  if (!isValid) return;

  emit('save', {
    ...form.value,
    completed: false
  });

  handleClose();
};
</script>
